﻿using JzSport.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JzSport.Api
{
    class GetFriendsListAction : AuthGetAction<Params.GetFriendsListParams,
        Results.GetFriendsListResult>
    {
        protected override ActionResult<Results.GetFriendsListResult> OnExecute(ActionContext context, 
            SysParameters sysParameters,
            Params.GetFriendsListParams opParams)
        {
            int limit = 25;
            int start = opParams.Page * limit;
            ServiceResult<PagedList<Model.Data.Friend>> serviceResult = new FriendsService().GetFriends(context.AccountId, start, limit);

            Results.GetFriendsListResult actionResult = new Results.GetFriendsListResult();

            if (serviceResult.ErrorCode == ErrorCode.NoError)
            {
                actionResult.Start = serviceResult.Data.Start;
                actionResult.Limit = serviceResult.Data.Limit;
                actionResult.Total = serviceResult.Data.Total;

                for (int index = 0; index < serviceResult.Data.Items.Count; index++)
                {
                    Results.GetFriendsListResult.FriendsItem item = new Results.GetFriendsListResult.FriendsItem();
                    item.Id = serviceResult.Data.Items[index].Id;
                    item.Name = serviceResult.Data.Items[index].Name;
                    item.NickName = serviceResult.Data.Items[index].NickName;
                    item.AvatarUrl = string.Format("{0}{1}", Configs.BaseWebUrl, serviceResult.Data.Items[index].AvatarUrl);
                    item.Phone = serviceResult.Data.Items[index].Phone;
                    item.City = serviceResult.Data.Items[index].City;
                    item.Sex = serviceResult.Data.Items[index].Sex;
                    
                    actionResult.Items.Add(item);
                }

                if (actionResult.Start + actionResult.Items.Count >= actionResult.Total)
                {
                    actionResult.IsTheEnd = true;
                }
                else
                {
                    actionResult.IsTheEnd = false;
                }

                return new ActionResult<Results.GetFriendsListResult>("1.0.1", true, serviceResult.ErrorCode,
                    ErrorCode.ToString(serviceResult.ErrorCode), actionResult);
            }
            return new ActionResult<Results.GetFriendsListResult>("1.0.1", false, serviceResult.ErrorCode,
                    ErrorCode.ToString(serviceResult.ErrorCode), actionResult);
        }
    }
}
